package com.fhc.view

import android.app.ActivityManager
import android.app.ActivityManager.RunningAppProcessInfo
import android.app.Application
import android.content.Context
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import jakarta.inject.Inject
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

private const val StopTimeoutMillis: Long = 5000

/**
 * A [SharingStarted] meant to be used with a [StateFlow] to expose data to the UI.
 *
 * When the UI stops observing, upstream flows stay active for some time to allow the system to
 * come back from a short-lived configuration change (such as rotations). If the UI stops
 * observing for longer, the cache is kept but the upstream flows are stopped. When the UI comes
 * back, the latest value is replayed and the upstream flows are executed again. This is done to
 * save resources when the app is in the background but let users switch between apps quickly.
 */
val WhileUiSubscribed: SharingStarted = SharingStarted.WhileSubscribed(StopTimeoutMillis)

data class UiStateTask(
    val isInInit: Boolean = true,  //用来区分画面是否初始化
    val toastMsgId: Int? = null,
    val toastMsgArgs: Array<Any>? = emptyArray<Any>(),
    val data: Any?,
) {
    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false

        other as UiStateTask

        if (isInInit != other.isInInit) return false
        if (toastMsgId != other.toastMsgId) return false
        if (!toastMsgArgs.contentEquals(other.toastMsgArgs)) return false
        if (data != other.data) return false

        return true
    }

    override fun hashCode(): Int {
        var result = isInInit.hashCode()
        result = 31 * result + (toastMsgId ?: 0)
        result = 31 * result + (toastMsgArgs?.contentHashCode() ?: 0)
        result = 31 * result + (data?.hashCode() ?: 0)
        return result
    }
}

enum class EnumAPPState {
    NULL,
    OFFLINE,
    ONLINE,
    EXCEPTION,
    UNKNOWN,
}


data class NFCBleStatus(var state: Int = -100,var bleMac: String = "", var info: String = "", var connectedTime: Long = -1){


}

@HiltViewModel
open class FhcAppViewModel @Inject constructor(
    app : Application
) : AndroidViewModel(app) {

    protected val context
        get() = getApplication<Application>()




    private val _sharedState = MutableStateFlow(0)
    val sharedState = _sharedState.asStateFlow()

    fun updateState() {
        _sharedState.value++
    }

    protected open fun  init() {
    }

    private val _loadingState = MutableStateFlow(GlobalLoadingState())
    val loadingState = _loadingState.asStateFlow()

    fun closeLoading() {
        _loadingState.update {
            GlobalLoadingState(isLoading = false, loadingText = null)
        }
    }
    fun showLoading(loadingText:String? = null) {
        if(loadingText != null) {
            _loadingState.update {
                GlobalLoadingState(isLoading = true, loadingText = loadingText, progressPercent = 15F, isProgress = true)
            }
        }else{
            _loadingState.update {
                GlobalLoadingState(isLoading = true, progressPercent = 15F, isProgress = true)
            }
        }
        viewModelScope.launch {
            delay(2000)
            _loadingState.update {
                GlobalLoadingState(isLoading = true, progressPercent = 35F, isProgress = true)
            }
            delay(2000)
            _loadingState.update {
                GlobalLoadingState(isLoading = true, progressPercent = 85F, isProgress = true)
            }
            delay(2000)
            closeLoading()
        }
    }

    fun showProgressLoading(progressPercent: Float) {
        _loadingState.update {
            GlobalLoadingState(isProgress = true, progressPercent = progressPercent)
        }
        viewModelScope.launch {
            delay(2000)
            closeLoading()
        }
    }



    // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   UI Init  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    protected val _toastMsg: MutableStateFlow<Int?> = MutableStateFlow(null)
    protected val _toastMsgArg: MutableStateFlow<Array<Any>> = MutableStateFlow(emptyArray<Any>())
    protected val _isInInit: MutableStateFlow<Boolean?> = MutableStateFlow(null)
     val uiState: StateFlow<UiStateTask> = combine(_toastMsg,_toastMsgArg,_isInInit) { toastMsg,toastMsgArg, isInInit ->
        UiStateTask(_isInInit.value == true, _toastMsg.value, _toastMsgArg.value, null)
    }.stateIn(
        scope = viewModelScope,
        started = WhileUiSubscribed,
        initialValue = UiStateTask(true, null, null, null)
    )

    private val _firstInitFlow = MutableStateFlow<Boolean>(true)
    val firstInitFlow: StateFlow<Boolean> = _firstInitFlow.asStateFlow()
    open fun firstInitFinished() {
        _firstInitFlow.update { false }
    }

    fun isAppInForeground(context: Context): Boolean {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningAppProcesses = activityManager.runningAppProcesses ?: return false

        for (processInfo in runningAppProcesses) {
            if (processInfo.processName == context.packageName) {
                // Importance_FOREGROUND indicates that the process is running in the foreground
                return processInfo.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND
            }
        }
        return false
    }



}





//class AppViewModel(application: Application) : AndroidViewModel(application) {
//    private val _user = MutableLiveData<User>()
//    val user: LiveData<User> get() = _user
//
//    fun setNameAge( name: String, age: Int) {
//        _user.value?.name = name
//        _user.value?.age = age
//    }
//
//    fun setState( appState: EnumAPPState) {
//        _user.value?.appState = appState
//    }
//
//    fun reset(name: String, age: Int, appState: EnumAPPState) {
//        _user.value = User(name, age, appState)
//    }
//}



//// 步骤2: 创建ViewModel的工厂并提供全局实例
//class AppViewModelFactory(private val application: Application) : ViewModelProvider.Factory {
//    private val viewModel by lazy { AppViewModel(application) }
//    override fun <T : ViewModel> create(modelClass: Class<T>): T {
//        viewModel.reset("",0, EnumAPPState.NULL)
//        return viewModel as T
//    }
//}


//
//    fun aaaa(): AppViewModel {
//        return  viewModelFactory.create(AppViewModel::class.java)
//    }
